package com.web.filemanage.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

import com.web.common.controller.AuthController;
import com.web.common.interceptor.BaseInterceptor;
import com.web.common.po.User;

public class FileInterceptor extends BaseInterceptor{
	
	public static final String FILE_ROLE_CHECK = "FILE_ROLE_CHECK";
	
	@Override    
    public boolean preHandle(HttpServletRequest request,  HttpServletResponse response, Object handler) throws Exception {    
 		
		User user = (User)request.getSession().getAttribute(AuthController.USER_INFO);
		HandlerMethod method = (HandlerMethod) handler;
		String methodName = method.getMethod().getName();
		
		//上传文件需要角色等级 》= 4
		if(methodName.equals("doUpload")){
			if(user.getUserRole() >= 4){
				return true;
			}
			else{
				request.getSession().setAttribute(FILE_ROLE_CHECK, "你的角色等级是："+user.getUserRole()+"\n"+"上传操作需要的角色等级：》=4");
				request.getRequestDispatcher("/filemanage/downloadDenied.jsp").forward(request, response);
				return false;
			}
		}
		
		//下载文件需要角色等级  》= 2
		else if(methodName.equals("download")){
			if(user.getUserRole() >= 2){
				return true;
			}
			else{
				request.getSession().setAttribute(FILE_ROLE_CHECK, "你的角色等级是："+user.getUserRole()+"\n"+"下载操作需要的角色等级：》=2");
				request.getRequestDispatcher("/filemanage/downloadDenied.jsp").forward(request, response);
				return false;
			}	
		}
		
		//其他操作不要求角色权限
		else{
			return true;
		}		
    }    
    
    /** 
     * 在业务处理器处理请求执行完成后,生成视图之前执行的动作    
     * 可在modelAndView中加入数据，比如当前时间 
     */  
    @Override    
    public void postHandle(HttpServletRequest request,    HttpServletResponse response, Object handler,    ModelAndView modelAndView) throws Exception {       

    }    
    
    /**  
     * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等   
     *   
     * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()  
     */    
    @Override    
    public void afterCompletion(HttpServletRequest request,    HttpServletResponse response, Object handler, Exception ex)    throws Exception {     
    
    
    
    }    
	
}
